package com.twu.biblioteca;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.Hashtable;


public class UserAccountsParser {

    private Hashtable<String,UserAccount> accountsList;

    public UserAccountsParser() {
        accountsList = new Hashtable<String, UserAccount>();
    }

    public Hashtable<String,UserAccount> getUserAccountsList() {
        return  accountsList;
    }

    public Hashtable<String, UserAccount> parseXml(Document xmlFile) {
        accountsList = new Hashtable<String, UserAccount>();
        if(xmlFile!=null){
            NodeList accountsNodeList = getAccountsNodeList(xmlFile);
                for(int accountsListIndex =0; accountsListIndex < accountsNodeList.getLength() ; accountsListIndex++){
                    Element accountNodeElement = (Element) accountsNodeList.item(accountsListIndex);
                    accountsList.put(getTextValueFromNode(accountNodeElement, "USERNAME"),
                            createUserAccountObj(accountNodeElement));
            }
        }

        return accountsList;
    }

    private UserAccount createUserAccountObj(Element accountNode) {
        return new UserAccount(getTextValueFromNode(accountNode, "USERNAME"),
                getTextValueFromNode(accountNode, "PASSWORD"), createUserInformationObj(accountNode));
    }

    private  UserInformation createUserInformationObj(Element userNode){
        return new UserInformation(getTextValueFromNode(userNode, "NAME"),
                getTextValueFromNode(userNode, "EMAIL"),
                getTextValueFromNode(userNode, "PHONE"));
    }

    private String getTextValueFromNode(Element nodeElement, String nodeLabel) {
        NodeList nodesList = nodeElement.getElementsByTagName(nodeLabel);

        if(nodesList.getLength() > 0)
            return nodesList.item(0).getTextContent();

        return "";
    }

    private NodeList getAccountsNodeList(Document xmlFile) {
        try
        {
            String xmlAccountLabel = "ACCOUNT";
            return xmlFile.getElementsByTagName(xmlAccountLabel);

        } catch (Exception e) {
            return (NodeList) new ArrayList();
        }
    }


}
